<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @close="closeDialog"
    @open="hamdleOpen"
  >
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>

    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="clickSubmit">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>

    </template>
  </el-dialog>
</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { reqGetUserDetailById, reqAssignRoles } from '@/api/employees'
export default {
  name: 'AssingRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      checkList: [],
      roleList: [],
      loading: false
    }
  },
  methods: {
    closeDialog() {
      this.$emit('update:showRoleDialog', false)
      this.checkList = []
    },
    hamdleOpen() {
      // 点击弹窗loding效果显示,等数据请求回来再关闭
      this.loading = true
      //   Promise.all([Promise对象1,Promise对象2,...]).then() 所有的Promise对象异步操作完成是,才调用then
      Promise.all([this.getRoleList(), this.getUserDetailById()]).then(() => {
        this.loading = false
      })
    },
    async getRoleList() {
      const { data: { rows }} = await reqGetRoleList(1, 100)
      //   console.log(res)
      this.roleList = rows
    },
    async getUserDetailById() {
      const { data } = await reqGetUserDetailById(this.userId) // 通过id获取员工基本信息,包含职业
      //   console.log(data)
      this.checkList = data.roleIds // 把获取到的
    },
    // 点击确定 更改角色
    async clickSubmit() {
      await reqAssignRoles(this.userId, this.checkList)
      this.$message.success('分配角色成功')
      this.closeDialog()
    }
  }
}
</script>
